<?php
/**
 * 获取毫秒时间戳
 * @return string
 */
function getMicroTime(){
    return substr(microtime(true)*1000,0,13);
}

/**
 * 生成唯一订单序列号
 * @return string
 */
function createOrderSn(){
    $order_id_main = date('YmdHis').rand(10000000,99999999);
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for($i=0; $i<$order_id_len; $i++){
        $order_id_sum += (int)(substr($order_id_main,$i,1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
    return $order_id;
}

/**
 * 获取HTML文本中的图片
 * @param String $content html文本
 * @param int $num 数量
 * @return string|array
 */
function getContentPic($content,$num=1){
    $pattern="/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
    preg_match_all($pattern,htmlspecialchars_decode($content),$match);
    if(!empty($match[1]) && $num == 1){
        return $match[1][0];
    }else{
        return $match[1];
    }
    return '';
}

/**
 * 生成全局唯一UUID
 * @return string
 */
function createUUID(){
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}

/**
 * 时间友好显示
 * @param null $time 时间戳
 * @return string
 */
function mdate($time = NULL) {
    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 （秒）
    $y = date('Y', $time)-date('Y', time());//是否跨年
    switch($t){
        case $t == 0:
            $text = '刚刚';
            break;
        case $t < 60:
            $text = $t . '秒前'; // 一分钟内
            break;
        case $t < 60 * 60:
            $text = floor($t / 60) . '分钟前'; //一小时内
            break;
        case $t < 60 * 60 * 24:
            $text = floor($t / (60 * 60)) . '小时前'; // 一天内
            break;
        case $t < 60 * 60 * 24 * 3:
            $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
            break;
        case $t < 60 * 60 * 24 * 30:
            $text = date('m-d H:i', $time); //一个月内
            break;
        case $t < 60 * 60 * 24 * 365&&$y==0:
            $text = date('m-d', $time); //一年内
            break;
        default:
            $text = date('Y-m-d', $time); //一年以前
            break;
    }
    return $text;
}

/**
 * 隐藏指定位置字符
 * @param string $string 原始字符
 * @param int $bengin 起始位置
 * @param int $len 隐藏长度
 * @param int $type 类型：0从左向右;1从右向左
 * @param string $glue 分隔符
 * @return string
 */
function hideStr($string, $bengin=0, $len = 4, $type = 0, $glue = "@") {
    if (empty($string))
        return false;
    $array = array();
    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }
    if ($type == 0) {
        for ($i = $bengin; $i < ($bengin + $len); $i++) {
            if (isset($array[$i]))
                $array[$i] = "*";
        }
        $string = implode("", $array);
    }else if ($type == 1) {
        $array = array_reverse($array);
        for ($i = $bengin; $i < ($bengin + $len); $i++) {
            if (isset($array[$i]))
                $array[$i] = "*";
        }
        $string = implode("", array_reverse($array));
    }else if ($type == 2) {
        $array = explode($glue, $string);
        $array[0] = hideStr($array[0], $bengin, $len, 1);
        $string = implode($glue, $array);
    } else if ($type == 3) {
        $array = explode($glue, $string);
        $array[1] = hideStr($array[1], $bengin, $len, 0);
        $string = implode($glue, $array);
    } else if ($type == 4) {
        $left = $bengin;
        $right = $len;
        $tem = array();
        for ($i = 0; $i < ($length - $right); $i++) {
            if (isset($array[$i]))
                $tem[] = $i >= $left ? "*" : $array[$i];
        }
        $array = array_chunk(array_reverse($array), $right);
        $array = array_reverse($array[0]);
        for ($i = 0; $i < $right; $i++) {
            $tem[] = $array[$i];
        }
        $string = implode("", $tem);
    }
    return $string;
}

/**
 * 二维数组排序
 * @param array $array 待排序数组
 * @param array $cols 排序方法,['键名'=>'SORT_ASC']
 */
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $eval = 'array_multisort(';
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;
}

/**
 * Base64图片保存
 * @param string $base64_image_content Base64码
 * @param string $image_path 保存路径
 * @return array
 */
function saveBase64Image($base64_image_content,$image_path){
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        if($type=='jpeg'){
            $type='jpg';
        }
        $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
        $image_url = $image_path.$image_name;
        if(!is_dir(app()->getRootPath().$image_path)){
            mkdir(app()->getRootPath().$image_path,0755,true);
        }
        //解码
        $decode=base64_decode(str_replace($result[1], '', $base64_image_content));
        if (file_put_contents(app()->getRootPath().$image_url, $decode)){
            $data['code']='0';
            $data['imageName']=$image_name;
            $data['image_url']=$image_url;
            $data['type']=$type;
            $data['msg']='保存成功！';
        }else{
            $data['code']='1';
            $data['imgageName']='';
            $data['image_url']='';
            $data['type']='';
            $data['msg']='图片保存失败！';
        }
    }else{
        $data['code']='1';
        $data['imgageName']='';
        $data['image_url']='';
        $data['type']='';
        $data['msg']='base64图片格式有误！';
    }
    return $data;
}

/*
 * Xml文件增加节点
 * @param $filename string 文件路径
 * @param $data array 追加数组
 * @param $nodename string 节点名称
 * @return boole
 */
function addXmlNode($filename,$data,$nodename){
    if(is_array($data) && !empty($data) && is_file($filename) && is_string($nodename)){
        $contents = file_get_contents($filename);
        $xml = @simplexml_load_string($contents);
        foreach($data as $key=>$value){
            foreach($data[$key] as $k=>$v){
                $item = $xml->addChild($nodename);
                $item->addChild($k,$v);
            }
        }
        $xml->asXML();
        $xmlDocument = new DOMDocument('1.0');
        $xmlDocument->preserveWhiteSpace = false;
        $xmlDocument->formatOutput = true;
        $xmlDocument->loadXML($xml->asXML(),LIBXML_NOERROR);
        $res = file_put_contents($filename,$xmlDocument->saveXML());
        return  $res !== false?true:$res;
    }
    return false;
}